<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            v-model:data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            @handleEvent="formHandleEvent"
          >
            <template v-slot:form-supplierName>
              <el-input
                v-model="formInfo.data.supplierName"
                class="not-mongolia"
                type="input"
                placeholder="请选择供应商"
                :disabled="true"
              >
                <template #append>
                  <el-icon @click="selectSupplier"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-filePathList>
              <UploadImg
                v-model:value="formInfo.data.filePathList"
                :action="action"
                :title="'附件'"
                :fileType="['png', 'jpg', 'jpeg', 'pdf']"
                :response-fn="handleResponse"
              />
            </template>
          </PageForm>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <PageFilter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button
                :disabled="
                  !(formInfo.data.supplierName && formInfo.data.settleType)
                "
                @click="addProduct"
                >添加待开票明细</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button
                :disabled="!tableInfo.selections.length"
                @click="removeProduct"
                >删除待开票明细</el-button
              >
            </template>
            <template v-slot:filter-receiptNumber>
              发票号：
              <el-input
                v-model="filterInfo.receiptNumber"
                style="width: 200px"
                placeholder="请输入发票号"
                clearable
              ></el-input>
            </template>
          </PageFilter>
          <div>
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :tab-index="false"
                :check-box="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :merge-data="tableInfo.mergeData"
                :merge-filed="tableInfo.mergeFiled"
                :isRowClickSelect="true"
                :isDynamic="true"
                :row-class-name="tableRowClassName"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-receiptNumber="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.receiptNumber`"
                    :rules="[
                      {
                        required: scope.$index >= 0,
                        message: '请输入发票号',
                        trigger: 'blur',
                      },
                    ]"
                  >
                    <el-input
                      v-model.lazy="scope.row.receiptNumber"
                      clearable
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-price="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.price`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoney,
                              trigger: ['blur', 'change'],
                            },
                            {
                              required: scope.$index >= 0,
                              message: '请输入单价',
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.price"
                      clearable
                      controls-position="right"
                      :precision="
                        $store.state.permission.systemConfig.price_precision
                      "
                      @change="changeNum($event, scope.row, `price`)"
                      :min="0"
                      :max="999999999999999"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-orderDescribeList="scope">
                  <div
                    v-for="(item, index) in scope.row.orderDescribeList"
                    :key="index"
                  >
                    <span>
                      {{
                        item.orderNo +
                        '-' +
                        item.settlementPrice +
                        '(元)-' +
                        item.calcQty
                      }}
                    </span>
                  </div>
                </template>
              </PageTable>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <AddProduct
      v-if="productInfo.visible"
      v-model:query="productInfo.query"
      :api="productInfo.api"
      v-model:show-dialog="productInfo.visible"
      @callback="selectProduct"
    />
    <individual
      v-if="individualInfo.visible"
      v-model:query="individualInfo.query"
      :selectData="individualInfo.selectData"
      v-model:show-dialog="individualInfo.visible"
      :idNotIn="individualInfo.idNotIn"
      @callback="individualCallback"
    />
    <!-- 选择供应商 -->
    <SelectSupplier
      v-if="supplierInfo.visible"
      @callback="callBackSupplier"
      v-model:showDialog="supplierInfo.visible"
      v-model:query="supplierInfo.query"
      :checkBox="false"
      :highlightRow="true"
    />
  </div>
</template>
<script setup name="receiptOrderModify">
import {
  getReceiptOrderDetailCustomizeListAll,
  getReceiptOrderById,
  updateReceiptOrder,
  createReceiptOrder,
  createReceiptOrderAndSave,
} from '@/api/receipt.js'
import { getCustomizeSetting } from '@/api/customize'
import AddProduct from './addProduct'
import individual from './individual'
import UploadImg from '@/components/UploadImg/index'
import axios from 'axios'
import moment from 'moment'
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'orderId', 'title', 'tableRow'])

const clickIndex = ref(null)
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const fullInfo = ref({
  btnList: [
    {
      label: '保存并提交',
      event: saveAndSubmit,
      show: !props.orderId && proxy.$permission('receiptOrder:saveAndSubmit'),
    },
    { label: '保存', event: save, show: true },
  ],
})
const formRefs = ref(undefined)
const formInfo = ref({
  ref: null,
  data: {
    filePathList: [],
    receiptDate: moment(new Date()).format('YYYY-MM-DD'),
  },
  fieldList: [
    {
      label: '发票号',
      value: 'receiptNumber',
      type: 'input',
      disabled: true,
    },
    {
      label: '发票类型',
      value: 'receiptType',
      type: 'select-model',
      code: 'receipt_type',
    },
    { label: '供应商', value: 'supplierName', type: 'slot' },
    {
      label: '开票金额',
      value: 'receiptAmount',
      type: 'input',
      disabled: true,
    },
    {
      label: '出入库金额',
      value: 'exportStoreAmount',
      type: 'input',
      disabled: true,
    },
    {
      label: '开票日期',
      value: 'receiptDate',
      type: 'date',
    },
    {
      label: '结算方式',
      value: 'settleType',
      type: 'select-model',
      multiple: true, 
      code: 'settlement_method',
      event: 'changeSettleType',
    },
    {
      label: '发票张数',
      value: 'receiptCount',
      type: 'number'
    },
    {
      label: '附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    receiptNumber: [
      {
        required: true,
        message: '请输入发票号',
        trigger: 'blur',
      },
    ],
    supplierName: [
      {
        required: true,
        message: '请选择供应商',
        trigger: 'blur',
      },
    ],
    settleType: [
      {
        required: true,
        message: '请选择结算方式',
        trigger: 'blur',
      },
    ],
    receiptDate: [
      {
        required: true,
        message: '请选择开票日期',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  receiptNumber: '',
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.orderId,
      },
    },
    queryParams: {},
  },
  // query: {
  //
  // },
  list: [
    {
      type: 'slot',
      label: '添加待开票明细',
      value: 'addProduct',
    },
    {
      type: 'slot',
      label: '删除待开票明细',
      value: 'removeProduct',
    },
    { type: 'slot', label: '发票号', value: 'receiptNumber' },
    {
      type: 'button',
      label: '一键设置发票号',
      event: batchReceiptNumberHandle,
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  mergeData: {},
  mergeFiled: ['sumAmount'],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '明细操作',
        event: _individual,
        show: true,
      },
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const productInfo = ref({
  visible: false,
  query: {
    // receiptSourceType: 1,
  },
})
const individualInfo = ref({
  visible: false,
  query: {},
  idNotIn: '',
  selectData: {},
})
const supplierInfo = ref({
  visible: false,
  query: {
    supplierAuth: 'supplierId',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    let sumAmount = 0
    let exportStoreAmount = 0
    let exportStoreAmountItem = 0
    let receiptNumberArr = []
    if (val.length) {
      val.forEach((item, index) => {
        if (item.receiptNumber) {
          receiptNumberArr.push(item.receiptNumber)
        }
        sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount)

        item.extDetails.forEach((row) => {
          exportStoreAmountItem = proxy.$fn.accMul(
            row.exportStorePrice || 0,
            row.calcQty
          )
          exportStoreAmount = proxy.$fn.accAdd(
            exportStoreAmount,
            exportStoreAmountItem
          )
        })
        item.qty = item.calcQty
        let orderDescribe = []
        item.orderDescribeList.forEach((el) => {
          let str = el.orderNo + '-' + el.settlementPrice + '(元)-' + el.calcQty
          orderDescribe.push(str)
        })
        item.orderDescribe = String(orderDescribe)
        item.tableIndex = index
      })
    }
    formInfo.value.data['receiptAmount'] = sumAmount
    formInfo.value.data['exportStoreAmount'] = exportStoreAmount
    if (receiptNumberArr.length) {
      receiptNumberArr = [...new Set(receiptNumberArr)]
    }
    formInfo.value.data['receiptNumber'] = String(receiptNumberArr)
  },
  { deep: true }
)

setData()
function setData() {
  let obj = {
    receiptNumber: {
      label: '开票号',
      value: 'receiptNumber',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    baseProductTypeValue: {
      label: '产品类型',
      value: 'baseProductTypeValue',
      asValue: 'baseProductType',
      componentType: 'select-model',
      code: 'new_product_type',
      show: false,
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      type: 'slot',
      minWidth: '150px',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function batchReceiptNumberHandle() {
  let receiptNumber = filterInfo.value.receiptNumber
  if (receiptNumber) {
    if (tableInfo.value.selections.length) {
      tableInfo.value.selections.forEach((row) => {
        row['receiptNumber'] = receiptNumber
      })
    } else {
      proxy.$message({
        message: '请选择需批量调发票号的明细！',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
  }
}
function formHandleEvent(event) {
  if (event === 'changeSettleType') {
    tableInfo.value.data = []
  }
}
function changeNum(e, row, str) {
  tableInfo.value.data.forEach((item) => {
    item.isChioce = false
  })
  let data = proxy.$fn.deepClone(tableInfo.value.data)
  let sumAmount = 0
  let amount = 0
  if (str === 'price') {
    sumAmount = proxy.$fn.accMul(e, row.calcQty || 0)
    row.extDetails.forEach((item) => {
      amount = proxy.$fn.accMul(e, item.calcQty || 0)
      item['price'] = e
      item['sumAmount'] = amount
    })
  } else if (str === 'calcQty') {
    sumAmount = proxy.$fn.accMul(e, row.price || 0)
  }
  row['sumAmount'] = sumAmount
  row.key = row.productId + row.batchNumber + row.price
  let list = data.filter(
    (item) => item.key === row.key && item.tableIndex !== row.tableIndex
  )
  if (list && list.length) {
    let receiptNumber = row.receiptNumber ? [row.receiptNumber] : []
    list.forEach((item) => {
      if (item.receiptNumber) {
        receiptNumber.push(item.receiptNumber)
      }
      row.extDetails = row.extDetails.concat(item.extDetails)
      row.orderDescribeList = row.orderDescribeList.concat(
        item.orderDescribeList
      )
    })
    if (receiptNumber && receiptNumber.length) {
      row.receiptNumber = receiptNumber.toString()
    }
    let sumCalcQty = 0
    row.extDetails.forEach((item) => {
      sumCalcQty = proxy.$fn.accAdd(sumCalcQty, item.calcQty || 0)
    })
    row.qty = sumCalcQty
    row.calcQty = sumCalcQty
    row.sumAmount = proxy.$fn.accMul(row.price || 0, row.calcQty || 0)
    tableInfo.value.data[row.tableIndex] = row
    let ids = list.map((item) => item.id)
    tableInfo.value.data = tableInfo.value.data.filter(
      (item) => !ids.includes(item.id)
    )
    tableInfo.value.data.forEach((item) => {
      item.isChioce = false
      if (item.id === row.id) {
        item.isChioce = true
      }
    })
  }
}
function callBackSupplier(row) {
  if (row) {
    formInfo.value.data['supplierName'] = row.supplierName
    formInfo.value.data['supplierId'] = row.supplierId
    productInfo.value.query.supplierId = row.supplierId
    individualInfo.value.query.supplierId = row.supplierId
    tableInfo.value.data = []
  }
}
function selectSupplier() {
  // 供应商
  supplierInfo.value.visible = true
}
function handleResponse(response, file) {
  return file
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = undefined
    if (props.orderId) {
      api = updateReceiptOrder
    } else {
      api =
        isSaveAndSubmit === true
          ? createReceiptOrderAndSave
          : createReceiptOrder
    }
    tableInfo.value.data.forEach((item) => {
      if (!item.orderId) {
        item.orderId = item.id
      }
      let orderDescribe = []
      item.orderDescribeList.forEach((el) => {
        let str = el.orderNo + '-' + el.settlementPrice + '(元)-' + el.calcQty
        orderDescribe.push(str)
      })
      item.orderDescribe = String(orderDescribe)
      item.extDetails.forEach((el) => {
        el.price = item.price
        el.businessOrderNo = el.businessOrderNo || el.orderNo
        el.businessOrderId = el.businessOrderId || el.orderId
      })
    })
    formInfo.value.data.details = tableInfo.value.data
    formInfo.value.data.orderSource = 1
    api(formInfo.value.data).then((res) => {
      if (res && res.success) {
        proxy.$emit('returnModify')
        showDialog.value = false
      }
    })
  })
}

function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function _individual(row, index) {
  individualInfo.value.query.settleType = formInfo.value.data.settleType
  individualInfo.value.query.supplierId = formInfo.value.data.supplierId
  individualInfo.value.visible = true
  individualInfo.value.query.productId = row.productId
  individualInfo.value.query.batchNumber = row.batchNumber
  let rowStr = row.productId + '&' + row.batchNumber
  let list = tableInfo.value.data.filter((item) => {
    let str = item.productId + '&' + item.batchNumber
    if (rowStr === str) {
      return item
    }
  })
  let ids = []
  if (list && list.length) {
    list.forEach((item) => {
      if (item.extDetails && item.extDetails.length) {
        item.extDetails.forEach((el) => {
          if (el.pendReceiptId) {
            ids.push(el.pendReceiptId)
          } else {
            ids.push(el.id)
          }
        })
      }
    })
  }
  individualInfo.value.idNotIn = ids.length ? ids.toString() : ''
  if (props.orderId) {
    individualInfo.value.query.receiptId = props.orderId
  }
  individualInfo.value.selectData = row
  clickIndex.value = index
}
function individualCallback(data, obj) {
  tableInfo.value.data[clickIndex.value]['extDetails'] = data
  tableInfo.value.data[clickIndex.value]['calcQty'] = obj.calcQty
  tableInfo.value.data[clickIndex.value]['sumAmount'] = obj.sumAmount
  let orderDescribeList = []
  if (data && data.length) {
    data.forEach((item) => {
      let obj = {
        orderNo: item.businessOrderNo,
        settlementPrice: item.exportStorePrice,
        calcQty: item.calcQty,
      }
      orderDescribeList.push(obj)
    })
  }
  tableInfo.value.data[clickIndex.value]['orderDescribeList'] =
    orderDescribeList
}
function addProduct() {
  productInfo.value.query.settleType = formInfo.value.data.settleType
  productInfo.value.query.supplierId = formInfo.value.data.supplierId
  productInfo.value.visible = true
  if (props.orderId) {
    productInfo.value.query.receiptId = props.orderId
  }
  let notId = []
  if (tableInfo.value.data && tableInfo.value.data.length > 0) {
    tableInfo.value.data.forEach((next) => {
      next.extDetails.forEach((item) => {
        notId.push(item.pendReceiptId)
      })
    })
    if (notId && notId.length > 0) {
      productInfo.value.query.idNotIn = notId.toString()
    }
    let ids = []
    tableInfo.value.data.forEach((row) => {
      if (row.orderDescribeList && row.orderDescribeList.length) {
        row.orderDescribeList.forEach((item) => {
          ids.push({
            productId: row.productId,
            batchNumber: row.batchNumber,
            orderNo: item.orderNo,
          })
        })
      }
    })
    if (ids && ids.length > 0) {
      productInfo.value.query.producAndBatchNumberdNotIn =
        JSON.stringify(ids).toString()
    }
  } else {
    productInfo.value.query.idNotIn = null
    productInfo.value.query.producAndBatchNumberdNotIn = null
  }
}
function selectProduct(rows) {
  if (rows && rows.length) {
    rows.forEach((item) => {
      item.key = item.productId + item.batchNumber + item.price
      if (item.extDetails && item.extDetails.length) {
        let orderDescribeList = []
        item.extDetails.forEach((el) => {
          el.businessOrderType = item.orderType
          let obj = {
            orderNo: el.orderNo,
            settlementPrice: el.settlementPrice,
            calcQty: el.calcQty,
          }
          orderDescribeList.push(obj)
        })
        item['orderDescribeList'] = orderDescribeList
      }
    })
    if (tableInfo.value.data && tableInfo.value.data.length) {
      let arr = []
      tableInfo.value.data.forEach((row) => {
        rows.forEach((item) => {
          if (row.key === item.key) {
            arr.push(row.key)
            row.orderDescribeList = row.orderDescribeList.concat(
              item.orderDescribeList
            )
            row.extDetails = row.extDetails.concat(item.extDetails)
            let calcQty = 0
            row.extDetails.forEach((item) => {
              calcQty = proxy.$fn.accAdd(item.calcQty || 0, calcQty)
            })
            row.calcQty = calcQty
            row.sumAmount = proxy.$fn.accMul(calcQty || 0, row.price || 0)
          }
        })
      })
      if (arr.length) {
        let newArr = []
        rows.forEach((item) => {
          if (!arr.includes(item.key)) {
            newArr.push(item)
          }
        })
        tableInfo.value.data = tableInfo.value.data.concat(newArr)
      } else {
        tableInfo.value.data = tableInfo.value.data.concat(rows)
      }
    } else {
      tableInfo.value.data = rows
    }
  }
}

function getMain() {
  getReceiptOrderById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
      tableInfo.value.data = res.data.details
      tableInfo.value.data.forEach((item) => {
        let data = []
        let orderDescribeList = item.orderDescribe.split(',')
        orderDescribeList.forEach((el) => {
          let arr = el.split('-')
          let obj = {
            orderNo: arr[0],
            settlementPrice: arr[1].split('(元')[0],
            calcQty: arr[2] ? arr[2] : '-' + arr[3],
          }
          data.push(obj)
        })
        item['orderDescribeList'] = data
        item.exportStorePrice = item.extDetails[0].exportStorePrice
        item.key = item.productId + item.batchNumber + item.price
      })
    }
  })
}
function getList() {
  getReceiptOrderDetailCustomizeListAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      let data = res.data[0]
      data = {
        ...data,
        calcQty: data.availableQty,
        sumAmount: proxy.$fn.accMul(
          data.availableQty || 0,
          data.settlementPrice || 0
        ),
        pendReceiptId: data.id,
        paice: data.settlementPrice || 0,
      }
      data.extDetails = [data]
      tableInfo.value.data = [data]
      tableInfo.value.data.forEach((item) => {
        let data = []
        let orderDescribeList = item.orderDescribe.split(',')
        orderDescribeList.forEach((el) => {
          let arr = el.split('-')
          let obj = {
            orderNo: arr[0],
            settlementPrice: arr[1].split('(元')[0],
            calcQty: arr[2] ? arr[2] : '-' + arr[3],
          }
          data.push(obj)
        })
        item['orderDescribeList'] = data
        item.key = item.productId + item.batchNumber + item.price
      })
    }
  })
}
function tableRowClassName({ row }) {
  if (row.isChioce) {
    return 'check-row'
  }
  return ''
}
function getCustomize() {
  let param = {
    tableKey:
      'receiptOrderDetailModify-com.slip.spd.entity.vo.receipt.ReceiptOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )

      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId
      if (props.orderId) {
        getMain()
      }
    }
  })
}
onMounted(() => {
  if (props.tableRow) {
    formInfo.value.data['settleType'] = props.tableRow.settleType
    formInfo.value.data['settleTypeValue'] = props.tableRow.settleTypeValue
    formInfo.value.data['supplierName'] = props.tableRow.supplierName
    formInfo.value.data['supplierId'] = props.tableRow.supplierId
    filterInfo.value.query.id = props.tableRow.id
    getList()
  }
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
})
</script>
